#include <iostream>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif
#include "ResourceManager.h"
#include "ErrorLogger.h"

namespace SypX
{
	ResourceManager::ResourceManager(void)
	{
	}

	ResourceManager::~ResourceManager(void)
	{
		std::map<String, Resource*>::iterator i = registry.begin();
		std::map<String, Resource*>::iterator j;
		while( i != registry.end())
		{
			if(i->second->getNumRef() == 0)
			{
				delete i->second;		//Delete the resource
				j = i;
				++j;
				registry.erase( i );	//Remove entry in the registry as well				
				i = j;
			}
			else
			{				
				SypX::ErrorLogger::getLogger() << "Resource Error: " << i->first.c_str() << ", " << i->second->getNumRef() << "\n";
				assert(false && "All references from some Resource(s) were not removed. Please ensure you have deleted all MeshInstances and removed all loaded Fonts.");				
				++i;
			}
		}
	}

	void ResourceManager::removeResource(Resource* res)
	{
		registry.erase(res->filename);
	}

	void ResourceManager::registerResource(Resource* res)
	{
		registry[res->getFileName()] = res;
	}

	Resource* ResourceManager::checkResource(const String& filename)
	{
		if( registry.find(filename) == registry.end() )
		{
			return 0;
		}
		return registry[filename];
	}

}